import { useMutation } from "@apollo/react-hooks";
import gql from "graphql-tag";
import { notification } from "antd";

import { QUERY } from "./useTable";
import { usePageContext } from "./useContext";
import { handleErrors } from "../../../utils/handleErrors";
import { useEffect } from "react";
import { useForm } from "./useForm";

const CREATE = gql`
  mutation CreateSysUser($user: CreateSysUserInput!) {
    createSysUser(user: $user) {
      id
    }
  }
`;

export const useCreate = ({ form }) => {
  const { handleClose } = useForm();
  const {
    state: {
      query,
      form: { isEdit, current }
    },
    dispatch
  } = usePageContext();

  const [createSysUser] = useMutation(CREATE, {
    onCompleted: ({ createSysUser }) => {
      if (createSysUser) {
        notification.success({ message: "新建用户成功！" });
        handleClose();
      }
    },
    onError: ({ graphQLErrors, networkError }) => {
      handleErrors({ graphQLErrors, networkError, form });
    },
    refetchQueries: [
      {
        query: QUERY,
        variables: {
          query
        }
      }
    ]
  });

  const handleSubmit = e => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        let { prefix, ...user } = { ...values };
        createSysUser({ variables: { user } });
      }
    });
  };

  useEffect(() => {
    if (!isEdit) {
      if (current) {
        dispatch({ type: "SET_FORM", payload: { handleSubmit } });
        dispatch({ type: "TOGGLE_MODAL", payload: true });
      } else {
        form.resetFields();
        dispatch({ type: "TOGGLE_MODAL", payload: false });
      }
    }
  }, [isEdit, current]);
};
